<template>
  <div>
    <!-- 使用自定义图片上传 -->
    <el-upload class="editor-img-uploader" :action="props.action" :show-file-list="false" :auto-upload="true"
      :headers="headers" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
    </el-upload>
    <!-- 此处注意写法v-model:content -->
    <QuillEditor ref="myQuillEditor" theme="snow" v-model:content="content" :options="data.editorOption"
      contentType="html" @update:content="setValue()" />
  </div>
</template>

<script lang="ts" setup>
import { QuillEditor, Quill } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { reactive, onMounted, ref, toRaw, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import "element-plus/es/components/message/style/css"; // 按需引入ElMessage样式失败，手动引入
import "element-plus/es/components/message-box/style/css";

const props = defineProps({
  action: {
    type:String, // 参数类型
    default: '', //默认值
    required: true, //是否必传
  },
})

// 图片上传
// 图片上传的后端地址
// let upLoadUrl = ref(
//   'http://127.0.0.1:3000/api/uploadimgPublishPro'
// );
// 上传文件时的请求头
let headers = reactive({
  Authorization: localStorage.getItem("token"),
});
// 图片上传成功返回图片地址
function handleAvatarSuccess(res: Response, file: any) {
  console.log('上传成功')
  // 如果上传成功
  if (res) {
    // 获取富文本实例
    let quill = toRaw(myQuillEditor.value).getQuill();
    // 获取光标位置
    let length = quill.selection.savedRange.index;
    // 插入图片，res为服务器返回的图片链接地址
    quill.insertEmbed(length, "image", res.url);
    // 调整光标到最后
    quill.setSelection(length + 1);
  } else {
    ElMessage({
      message: "提交失败！",
      type: "error",
    });
  }
}
// 图片上传前拦截
function beforeAvatarUpload(file: any) {
  console.log('图片上传拦截')
  console.log(file)
  const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
  const isJPG = type.includes(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage({
      message: "图片格式错误",
      type: "success",
    });
  }
  if (!isLt2M) {
    ElMessage({
      message: "上传图片不能超过 2MB",
      type: "success",
    });
  }
  return isJPG && isLt2M;
}


// const props = defineProps(['value','upLoadUrl'])
const emit = defineEmits(['updateValue'])
const content = ref('')
const myQuillEditor = ref()
const fileBtn = ref()
const data = reactive({
  content: '',
  editorOption: {
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'header': 1 }, { 'header': 2 }],
        ['image'],
        [{ 'direction': 'rtl' }],
        [{ 'color': [] }, { 'background': [] }]
      ],
    },
    placeholder: '请输入内容...'
  }
})
const imgHandler = (state: any) => {
  if (state) {
    let elUpdateElmt = document.querySelector(".editor-img-uploader>.el-upload") as HTMLElement;
    elUpdateElmt.click();
    // fileBtn.value.click()
  } else {
    Quill.format("image", true);
  }
}
// 抛出更改内容，此处避免出错直接使用文档提供的getHTML方法
const setValue = () => {
  const text = toRaw(myQuillEditor.value).getHTML()
  emit('updateValue', text)
}

// 初始化编辑器
onMounted(() => {
  const quill = toRaw(myQuillEditor.value).getQuill()
  if (myQuillEditor.value) {
    quill.getModule('toolbar').addHandler('image', imgHandler)
  }

  nextTick(function () {
    let quill = toRaw(myQuillEditor.value).getQuill();
    quill.enable(true);
    quill.blur();
    document.documentElement.scrollTop = 0;
  });
})

</script>

<style lang="less" scoped>
// 调整样式
:deep(.ql-editor) {
  min-height: 180px;

  img {
    max-width: 50%;
  }
}

:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>